package com.mayikt;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.Lock;

/**
 * @ClassName MayiktExecutor
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class MayiktExecutor {
    /**
     * 存放一直正在运行的线程
     */
    private List<WorkThread> workThreads;

    /**
     * 执行我们的任务的容器
     */
    private BlockingQueue<Runnable> taskRunnable;
    private volatile boolean flag = true;


    public MayiktExecutor(int workThreadCount, int taskRunnableCount) {
        workThreads = new ArrayList<>(workThreadCount);
        taskRunnable = new LinkedBlockingDeque<>(taskRunnableCount);
        for (int i = 0; i < workThreadCount; i++) {
            WorkThread workThread = new WorkThread();
            workThread.start();
            workThreads.add(workThread);
        }

    }

    class WorkThread extends Thread {
        @Override
        public void run() {
            while (flag || taskRunnable.size() > 0) {
                Runnable runnable = taskRunnable.poll();
                if (runnable != null) {
                    runnable.run();
                }
            }
        }
    }

    public synchronized void stop() {
        this.flag = false;
    }

    public void execute(Runnable runnable) {
        taskRunnable.add(runnable);
    }

    public static void main(String[] args) {
        MayiktExecutor mayiktExecutor = new MayiktExecutor(2, 12);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            mayiktExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + "," + finalI));
        }
        mayiktExecutor.stop();

    }
}
